# 设置UTF8编码
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 获取当前目录的完整路径
$projectPath = $PWD.Path
Write-Host "Project path: $projectPath"

# 检查Python环境
$pythonPath = (Get-Command python -ErrorAction SilentlyContinue).Source
if (-not $pythonPath) {
    Write-Host "Error: Python not found. Please install Python and add to PATH."
    exit 1
}
Write-Host "Using Python path: $pythonPath"

# 清理现有虚拟环境
$venvPath = Join-Path $projectPath "quant_env"
if (Test-Path $venvPath) {
    Write-Host "Removing existing virtual environment..."
    try {
        # 先尝试结束所有Python进程
        Get-Process | Where-Object { $_.Path -like "*$venvPath*" } | Stop-Process -Force
        Start-Sleep -Seconds 2  # 等待进程完全结束
        
        # 使用cmd.exe删除目录（有时比PowerShell的Remove-Item更可靠）
        cmd /c "rd /s /q `"$venvPath`""
        Start-Sleep -Seconds 1  # 等待删除完成
        
        if (Test-Path $venvPath) {
            Write-Host "Warning: Could not remove old environment completely"
        }
    }
    catch {
        Write-Host "Warning: Failed to remove old environment: $($_.Exception.Message)"
    }
}

# 创建新的虚拟环境
Write-Host "Creating virtual environment..."
try {
    # 确保目录不存在
    if (Test-Path $venvPath) {
        Write-Host "Attempting final cleanup..."
        Remove-Item -Recurse -Force $venvPath -ErrorAction SilentlyContinue
    }
    
    # 创建新环境
    & $pythonPath -m venv $venvPath --clear
    Start-Sleep -Seconds 2  # 等待创建完成
}
catch {
    Write-Host "Error creating virtual environment: $($_.Exception.Message)"
    exit 1
}

# 设置虚拟环境路径
$venvPythonPath = Join-Path $venvPath "Scripts\python.exe"
$venvPipPath = Join-Path $venvPath "Scripts\pip.exe"

# 验证虚拟环境
if (-not (Test-Path $venvPythonPath) -or -not (Test-Path $venvPipPath)) {
    Write-Host "Error: Virtual environment creation failed"
    exit 1
}

# 激活虚拟环境
Write-Host "Activating virtual environment..."
$activateScript = Join-Path $venvPath "Scripts\Activate.ps1"
if (Test-Path $activateScript) {
    . $activateScript
}
else {
    Write-Host "Error: Activation script not found"
    exit 1
}

# 升级pip
Write-Host "Upgrading pip..."
try {
    & $venvPythonPath -m pip install --upgrade pip --no-cache-dir
}
catch {
    Write-Host "Warning: Failed to upgrade pip: $($_.Exception.Message)"
}

# 设置pip镜像
Write-Host "Setting pip mirror..."
& $venvPythonPath -m pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

# 安装核心依赖
Write-Host "Installing core dependencies..."
$core_packages = @(
    "apscheduler",
    "pandas",
    "numpy",
    "requests",
    "beautifulsoup4",
    "python-dotenv"
)

foreach ($package in $core_packages) {
    Write-Host "Installing $package..."
    try {
        & $venvPythonPath -m pip install $package --no-cache-dir
    }
    catch {
        Write-Host "Warning: Failed to install $package : $($_.Exception.Message)"
    }
}

# 安装其他依赖
Write-Host "Installing remaining dependencies..."
$requirementsPath = Join-Path $projectPath "requirements.txt"
try {
    & $venvPythonPath -m pip install -r $requirementsPath --no-cache-dir
}
catch {
    Write-Host "Warning: Failed to install dependencies: $($_.Exception.Message)"
}

# 验证安装
Write-Host "Verifying installation..."
$verifyScript = @'
from apscheduler.schedulers.blocking import BlockingScheduler
print("APScheduler installation successful!")
'@

try {
    & $venvPythonPath -c $verifyScript
    Write-Host "Core dependencies installed successfully!"
}
catch {
    Write-Host "Warning: Installation verification failed: $($_.Exception.Message)"
}

Write-Host @'
Installation complete!
Notes:
1. Virtual environment is activated in ./venv
2. Ensure virtual environment is activated before running
3. To activate: .\venv\Scripts\Activate
4. To deactivate: deactivate
'@ 